var baseIcon;
var letter;
var letteredIcon;
var point;
var marker;

function createMarker(point, html, letteredIcon) {
  	var marker = new GMarker(point, { icon:letteredIcon });
    GEvent.addListener(marker, "click", function() {
    	marker.openInfoWindowHtml('<div align="left">' + html + '</div>');
   	});
    marker.icon = 'b';
    // save the info we need to use later for the side_bar
    return marker;
}


function gmap_zoom_in() {
	point = gmap.fromContainerPixelToLatLng(clickedPixel)
    gmap.zoomIn(point,true);
	$(oContextMenu).hide();
}

function gmap_zoom_out() {
	point = gmap.fromContainerPixelToLatLng(clickedPixel)
    gmap.setCenter(point,gmap.getZoom()-1);
	$(oContextMenu).hide();
}


function gmap_centre_map() {
	point = gmap.fromContainerPixelToLatLng(clickedPixel)
   	gmap.setCenter(point);
	$(oContextMenu).hide();
};


function add_icon_to_gmap(oMarker, sNextLetter, sLatLong) {
	letteredIcon.image = 'http://www.google.com/mapfiles/marker' + sNextLetter + '.png';
		
	var aLatLong = sLatLong.split(',');
		
	point = new GLatLng($.trim(aLatLong[0]), $.trim(aLatLong[1])); 
	marker = createMarker(point, '', letteredIcon);
	$(oMarker).data('marker', marker);
	gmap.addOverlay(marker);
}


function gmap_add_marker() {
	var sLatLong = gmap.fromContainerPixelToLatLng(clickedPixel).toString();

	sLatLong = sLatLong.substr(1, sLatLong.length - 2);
	
	$(oContextMenu).hide();
	
	$.post('/admin/gmaps_ajax/add_marker', { sLatLong : sLatLong }, function(data) {
		var sNextLetter = 'A';
		
		if ($('.gmap_marker').length > 0) {
			$('.gmap_marker_nm').removeClass('gmap_marker_nm');
			
			sNextLetter = $('.gmap_marker_icon:last').children('option:selected').next().val();
		}
		
		$('#gmap_marker_cont').append(data.sContent);
		
		$('.gmap_marker:last').addClass('gmap_marker_nm');
		
		$('.gmap_marker_icon:last').val(sNextLetter).trigger('change');
		
		/* now add it to google map */
		add_icon_to_gmap($('.gmap_marker:last'), sNextLetter, sLatLong);
		
	}, 'json');
	
	
};



function gmap_default_location() {
	var point = gmap.fromContainerPixelToLatLng(clickedPixel)
   	gmap.setCenter(point);
	var sLatLong = $.trim(gmap.getCenter().toString());
	sLatLong = sLatLong.substr(1, sLatLong.length - 2);
	
	var aLatLong = sLatLong.split(',');
	
	$('#gmap_lat').html($.trim(aLatLong[0]));
	$('#gmap_long').html($.trim(aLatLong[1]));
	$(oContextMenu).hide();
	
}




$(document).ready(
	function() {

		if (GBrowserIsCompatible()) {
        	gmap = new GMap2(document.getElementById("gmap_map_cont"));
			gmap.setMapType(G_HYBRID_MAP); 
		    gmap.addControl(new GLargeMapControl());
		   	gmap.addControl(new GMapTypeControl());
		    gmap.enableContinuousZoom();
    		gmap.enableScrollWheelZoom();
			gmap.enableGoogleBar();
			
	        gmap.setCenter(new GLatLng($('#gmap_lat').html(), $('#gmap_long').html()), parseInt($('#gmap_zoom').val(), 10));		
			
			baseIcon = new GIcon();
		    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		    baseIcon.iconSize = new GSize(20, 34);
		    baseIcon.shadowSize = new GSize(37, 34);
		    baseIcon.iconAnchor = new GPoint(9, 34);
		    baseIcon.infoWindowAnchor = new GPoint(9, 2);
		    baseIcon.infoShadowAnchor = new GPoint(18, 25);
					
			letteredIcon = new GIcon(baseIcon);		
			
			oContextMenu = document.createElement('div');
			$(oContextMenu).css({ 
			 	display : 'none',
				backgroundColor : '#CECECE', 
				width : '140px',
				fontSize : '11px',
				color : '#333'
			}).html($('#gmap_context_menu').html()).children('div').css({
				cursor: 'pointer',
				margin: '1px',
				padding: '3px',
				backgroundColor: '#FFF'
			}).hover(function() {
				$(this).css({ backgroundColor : '#DDD'});
			}, function() {
				$(this).css({ backgroundColor : '#FFF'});
			});
			
			gmap.getContainer().appendChild(oContextMenu);
			
			// === listen for singlerightclick ===
		    GEvent.addListener(gmap,"singlerightclick",function(pixel,tile) {
		    	// store the "pixel" info in case we need it later
		        // adjust the context menu location if near an egde
		        // create a GControlPosition
		        // apply it to the context menu, and make the context menu visible
		        clickedPixel = pixel;
		        var x=pixel.x;
		        var y=pixel.y;
		        if (x > gmap.getSize().width - 120) { x = gmap.getSize().width - 120 }
		        if (y > gmap.getSize().height - 100) { y = gmap.getSize().height - 100 }
		        var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));  
		        pos.apply(oContextMenu);
		        $(oContextMenu).show();
		  	});
			
			
			GEvent.addListener(gmap, "click", function() {
		    	 $(oContextMenu).hide();
		   	});
			
      	}
		
		
		$('.gmap_marker').each(
			function(nr) {
				add_icon_to_gmap(this, $('.gmap_marker_icon:eq(' + nr + ')').val(), $('.gmap_marker_lat:eq(' + nr + ')').html() + ',' + $('.gmap_marker_long:eq(' + nr + ')').html());
			}
		);
		
		
		$('.gmap_marker_remove').live('click', function() {
			var oObj = $(this).parent().parent();
			
			gmap.removeOverlay($(oObj).data('marker'));
			
			$(oObj).slideUp(500, function() {
				$(this).remove();
			});
		});
		
		
		$('.gmap_marker_icon').live('change', function() {
			$(this).parent().parent().prev().children('.gmap_marker_marker:first').children('.gmap_marker_marker_icon').html('(' + $(this).val() + ')');
		});
		
		
		$('.gmap_marker_title').live('keyup', function() {
			$(this).parent().parent().parent().children('div:first').children('div:first').children('.gmap_marker_marker_title').html($(this).val());
		});
		
		$('.gmap_marker_icon').trigger('change');
		$('.gmap_marker_title').trigger('keyup');
		
		
		
		// now add all the markers
		
		$('#gmap_save_gmap').bind('click', function() {
			if ($('.gmap_marker').length === 0) {
				alert('<?php echo addslashes($aMessages['admin_gmaps_no_markers']); ?>');
				return;
			}
			
			
			var oGmapData = {};
			
			oGmapData.sGmapTitle = $('#gmap_title').val();
			
			if (val_is_empty(oGmapData.sGmapTitle) === true) {
				alert('<?php echo addslashes($aMessages['admin_gmaps_no_gmap_title']); ?>');
				return;
			}
			
			
			oGmapData.iGmapWidth = $('#gmap_width').val();
			
			if (val_is_empty(oGmapData.iGmapWidth) === true) {
				alert('<?php echo addslashes($aMessages['admin_gmaps_no_gmap_width']); ?>');
				return;
			}
			
			
			oGmapData.iGmapHeight = $('#gmap_height').val();
			
			if (val_is_empty(oGmapData.iGmapHeight) === true) {
				alert('<?php echo addslashes($aMessages['admin_gmaps_no_gmap_height']); ?>');
				return;
			}
			
			
			oGmapData.fGmapLat = $('#gmap_lat').html();
			
			if (val_is_empty(oGmapData.fGmapLat) === true) {
				alert('<?php echo addslashes($aMessages['admin_gmaps_no_gmap_lat']); ?>');
				return;
			}
			
			
			oGmapData.fGmapLong = $('#gmap_long').html();
			
			if (val_is_empty(oGmapData.fGmapLong) === true) {
				alert('<?php echo addslashes($aMessages['admin_gmaps_no_gmap_long']); ?>');
				return;
			}
			
			
			oGmapData.iGmapZoom = $('#gmap_zoom').val();
			
			if (val_is_empty(oGmapData.iGmapZoom) === true) {
				alert('<?php echo addslashes($aMessages['admin_gmaps_no_gmap_zoom']); ?>');
				return;
			}
			
			oGmapData.iGmapVersionId = oGmap.version_id;
			
			
			$.post('/admin/gmaps_ajax/get_version_number', oGmapData, function(data) {
				
				var iVersionId = data.iVersionId;
				
				var oGmapMarker;
				
				$('.gmap_marker').each(
					function(nr) {
						oGmapMarker = {};
						
						oGmapMarker.iVersionId = iVersionId
						oGmapMarker.sMarkerIcon = $('.gmap_marker_icon:eq(' + nr + ')').val();
						oGmapMarker.fMarkerLat = $('.gmap_marker_lat:eq(' + nr + ')').html();
						oGmapMarker.fMarkerLong = $('.gmap_marker_long:eq(' + nr + ')').html();
						oGmapMarker.sMarkerTitle = $('.gmap_marker_title:eq(' + nr + ')').val();
						oGmapMarker.sMarkerDesc = $('.gmap_marker_desc:eq(' + nr + ')').val();
						oGmapMarker.iMarkerPos = nr;
						
						$.post('/admin/gmaps_ajax/add_markers_to_version', oGmapMarker, function(data) {
						
						}, 'json');
					}
				);
			}, 'json');
			
			
		});
		
	
	}
);